package controllers;

import beans.PageBean;
import beans.UserBean;
import play.Play;
import play.cache.Cache;
import play.libs.Codec;
import play.libs.Images;
import play.mvc.*;
import utils.Config;
import utils.MessageUtil;
import utils.SessionUtils;
import utils.StringUtils;
import beans.WebServiceBean;
import models.*;
import java.util.List;

/**
 * 
 * @author xieyicheng
 *
 */
public class Users extends Controller {
    /**
     * 管理员登陆
     */
    public static void loginPage(){
        MessageUtil.cleanMsg(Scope.Flash.current());
    	render();
    }
    /**
     * 改名验证码
     * @param randomID
     */
    public static void changeCode(String randomID){
    	Cache.delete(randomID);
    	String ID = Codec.UUID();
    	//返回新的注册码id，供ajax调用
    	WebServiceBean bean = new WebServiceBean();
    	bean.result = 0;
    	bean.data = ID;
    	renderJSON(bean);
    }
    /**
     * 获取验证码
     * @param id
     */
    public static void captcha(String id) {
        Images.Captcha captcha = Images.captcha();
        if( Cache.get(id)==null){
            System.out.println("captcha_id = "+id);
            String code = captcha.getText("#000000");
            Cache.set(id, code, "10mn");
            renderBinary(captcha);
        }

    }

    /**
     * 管理员登陆
     * @param account
     */
    public static void adminLogin(User account){
    	if(account.isAllNotNull()){
    		
    		User user = User.findByUsername(account.account);
    		if(user!=null){
                if(user.authority!=User.Admin&&user.authority!=User.SuperAdmin){
                    MessageUtil.generateErrorMsg("你没有管理员权限");
                    loginPage();
                }
                if(user.password.equals(account.password)){
                    session.put("Admin_key","true");
                    Articles.showArticle(0,1);
                }
                else{
                    MessageUtil.generateErrorMsg("密码错误");
                    loginPage();
                }
    		}
    		else{
    			MessageUtil.generateErrorMsg("账号不存在");
    			loginPage();
    		}
    	}
    	else{
    		MessageUtil.generateErrorMsg("账号或者密码错误");
    		loginPage();
    	}
    }
    /**
     * 登出
     */
    public static void LoginOut(){
		SessionUtils.clear();
		loginPage();
    }

    /**
     * 验证权限
     */
    private static void checkAdmin(){
    	if(SessionUtils.getUserId()==null){
			loginPage();
			MessageUtil.generateInfoMsg("请先登陆");
		}
		else{
			User user = SessionUtils.getLoginUser();
            if(user.authority<1){
                loginPage();
                MessageUtil.generateInfoMsg("权限不够");
            }
		}
    }




}